/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.remote.support;

import com.googlecode.actorom.Actor;
import com.googlecode.actorom.impl.remote.RemoteAddress;
import com.googlecode.actorom.impl.remote.channel.MessageChannelConnector;
import com.googlecode.actorom.impl.remote.channel.protocol.MessageCommand;
import com.googlecode.actorom.support.ActorExecutionException;
import com.googlecode.actorom.support.ActorInvocationException;
import java.io.IOException;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class RemoteActorProxy implements Actor {

    private final RemoteAddress address;
    private final MessageChannelConnector channelConnector;

    public RemoteActorProxy(RemoteAddress address) {
        this.address = address;
        channelConnector = new MessageChannelConnector(address.getHost(), address.getPort());
    }

    public void send(Object message) {
        try {
            channelConnector.connect();
            boolean successful = channelConnector.send(new MessageCommand(address, message));
            if (!successful) {
                throw new ActorInvocationException("Error while sending message to remote actor: " + address);
            }
        } catch (IOException ex) {
            throw new ActorExecutionException(ex.getMessage(), ex);
        } finally {
            channelConnector.disconnect();
        }
    }
}
